<?php
/**
 * Created by jinqiang on 2025/5/19 17:56.
 * Copyright (c) 2025, Your Company. All rights reserved.
 */


namespace App\Http\Services\Soa;


use App\Http\Models\Mysql\Number5Table;
use App\Http\Models\Mysql\ProductSubcontractTable;
use App\Http\Models\Mysql\SsyStyleImagesTable;
use App\Http\Models\Mysql\StyleBomColourConfigTable;
use App\Http\Models\Mysql\StyleBomSizeConfigTable;
use App\Http\Models\Mysql\StyleBomTable;
use App\Http\Models\Mysql\StyleColourTable;
use App\Http\Models\Mysql\StylePrintingTable;
use App\Http\Models\Mysql\StyleT50Table;
use App\Http\Models\Mysql\StyleTable;
use App\Http\Models\Mysql\VerifyPriceBomTable;
use App\Http\Models\Mysql\VerifyPriceItemTable;
use App\Http\Models\Mysql\VerifyPricePrintingTable;
use App\Http\Models\Mysql\VerifyPriceT59Table;
use App\Http\Models\Mysql\VerifyPriceT76Table;
use App\Http\Models\Mysql\VerifyPriceTable;
use App\Http\Repository\LogRepository;
use Illuminate\Support\Facades\DB;

class VerifyPriceService
{
    public function search($param)
    {
        $conn = (new VerifyPriceTable());
        if($param['t73_id'] ?? ""){
            $conn = $conn->where('t73_id', (Int)$param['t73_id']);
        }
        if($param['type_no'] ?? ""){
            if(preg_match("/^[a-zA-Z]/is", $param['type_no'])){
                $conn = $conn->where('style_number', 'like', $param['type_no']."%");
            }else{
                $conn = $conn->where('style_number', 'like', "%".$param['type_no']."%");
            }
        }
        if($param['type_name'] ?? ""){
            $conn = $conn->where('style', 'like', "%".$param['type_name']."%");
        }
        if($param['number'] ?? ""){
            if(preg_match("/^[a-zA-Z]/is", $param['number'])){
                $conn = $conn->where('number', 'like', $param['number']."%");
            }else{
                $conn = $conn->where('number', 'like', "%".$param['number']."%");
            }
        }
        if(isset($param['state']) && $param['state'] != ""){
            $conn = $conn->where('state', (Int)$param['state']);
        }
        if($param['creator'] ?? ""){
            $conn = $conn->where('creator', $param['creator']);
        }
        $res = $conn->orderBy('id', 'desc')->paginate((Int)$param['limit'])->toArray();
        //款式图片
        $typeNoList = array_column($res['data'], 'style_number');
        $imgList = (new SsyStyleImagesTable())->whereIn('type_no', $typeNoList)->get(['type_no', 'thumb_images'])->toArray();
        $imgMap = array_column($imgList, 'thumb_images', 'type_no');
        foreach ($res['data'] as &$item){
            $item['creation_time'] = date('Y-m-d', $item['creation_time']+1512460800);
            $item['img'] = $imgMap[$item['style_number']] ?? "";
        }
        unset($item);
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function del($id)
    {
        $priceObj = (new VerifyPriceTable())->where('id', $id)->first()->toArray();
        if($priceObj['state'] == 1){
            return ['code' => -1, 'msg' => '删除失败：当前核价单已锁定'];
        }
        $exist = (new ProductSubcontractTable())->where('verify_price_number', $priceObj['number'])->exists();
        if($exist){
            return ['code' => -1, 'msg' => '删除失败：该单据已被依赖'];
        }
        (new VerifyPriceTable())->deleteData($id);//主表
        (new VerifyPriceBomTable())->deleteDataWhere(['verify_price_id' => $id]);//物料清单
        (new VerifyPriceItemTable())->deleteDataWhere(['verify_price_id' => $id]);//加工项目
        (new VerifyPricePrintingTable())->deleteDataWhere(['verify_price_id' => $id]);//印花BOM
        (new VerifyPriceT59Table())->deleteDataWhere(['verify_price_id' => $id]);//绣花BOM
        (new VerifyPriceT76Table())->deleteDataWhere(['verify_price_id' => $id]);//其他费用
        //写入操作日志
        $user = auth()->guard("api")->user();
        LogRepository::setOperateLog($user->name, "单据删除,款号:{$priceObj['style_number']}", $priceObj['number'], 3);
        return ['code' => 0];
    }

    public function lock($id, $state)
    {
        return (new VerifyPriceTable())->updateData($id, ['state' => $state]);
    }

    public function detail($id)
    {
        $verifyPriceObj = (new VerifyPriceTable())->where('id', $id)->first()->toArray();//主表
        //款式图片
        $imageObj = (new SsyStyleImagesTable())->where('type_no', $verifyPriceObj['style_number'])->first(['images']);
        $verifyPriceObj['img'] = $imageObj->images ?? "";
        //物料清单
        $verifyPriceBomList = (new VerifyPriceBomTable())->where('verify_price_id', $id)->get()->toArray();
        foreach ($verifyPriceBomList as &$item){
            $item['f57'] = ($item['f57'] * 100) ?: "";
            $item['amount'] = (Double)$item['amount'] ?: "";
            $item['price'] = (Double)$item['price'] ?: "";
            $item['f56'] = (Double)$item['f56'] ?: "";
        }
        unset($item);
        //加工项目
        $verifyPriceItemList = (new VerifyPriceItemTable())->where('verify_price_id', $id)->get()->toArray();
        foreach ($verifyPriceItemList as &$item){
            $item['f58'] = ($item['f58'] * 100) ?: "";
            $item['count'] = (Double)$item['count'] ?: "";
            $item['price'] = (Double)$item['price'] ?: "";
        }
        unset($item);
        //绣花BOM
        $verifyPriceT59List = (new VerifyPriceT59Table())->where('verify_price_id', $id)->get()->toArray();
        foreach ($verifyPriceT59List as &$item){
            $item['f60'] = ($item['f60'] * 100) ?: "";
            $item['f55'] = (Double)$item['f55'];
            $item['f54'] = (Double)$item['f54'];
        }
        unset($item);
        //印花BOM
        $verifyPricePrintingList = (new VerifyPricePrintingTable())->where('verify_price_id', $id)->get()->toArray();
        foreach ($verifyPricePrintingList as &$item){
            $item['price'] = (Double)$item['price'];
        }
        unset($item);
        //其他费用
        $verifyPriceT76List = (new VerifyPriceT76Table())->where('verify_price_id', $id)->get()->toArray();
        foreach ($verifyPriceT76List as &$item){
            $item['f58'] = ($item['f58'] * 100) ?: "";
            $item['count'] = (Double)$item['count'];
            $item['price'] = (Double)$item['price'];
        }
        unset($item);
        return [
            'data' => $verifyPriceObj,
            'bom_list' => $verifyPriceBomList,
            'item_list' => $verifyPriceItemList,
            'printing_list' => $verifyPricePrintingList,
            't59_list' => $verifyPriceT59List,
            't76_list' => $verifyPriceT76List,
        ];
    }

    public function getStyleBom($styleNumber)
    {
        $styleList = (new StyleTable())->where(function ($query) use($styleNumber) {
            if(preg_match("/^[a-zA-Z]/is", $styleNumber)){
                $query->where('number', 'like', $styleNumber."%");
            }else{
                $query->where('number', 'like', "%".$styleNumber."%");
            }
        })->get()->toArray();
        $styleNumbers = array_column($styleList, 'number');
        $styleMap = array_column($styleList, null, 'id');
        $styleIds = array_column($styleList, 'id');
        //款号图片
        $imageList = (new SsyStyleImagesTable())->whereIn('type_no', $styleNumbers)->get(['type_no', 'images'])->toArray();
        $imageMap = array_column($imageList, 'images', 'type_no');
        //款号颜色
        $styleColourList = (new StyleColourTable())->whereIn('style_id', $styleIds)->orderBy('style_id', 'desc')->get(['id', 'style_id', 'colour'])->toArray();
        //款号颜色 & BOM 关联关系
        $styleBomColourConfigList = (new StyleBomColourConfigTable())->whereIn('style_id', $styleIds)->get()->toArray();
        $styleBomColourConfigMap = [];
        foreach ($styleBomColourConfigList as $item){
            foreach ($styleColourList as $colourItem){
                if(empty($item['style_colour_id']) || $colourItem['id'] == $item['style_colour_id']){
                    $styleBomColourConfigMap[$item['style_id']][$item['is_product']][$colourItem['id']][] = $item['style_bom_id'];
                }
            }
        }
        //获取大货BOM
        $styleBomList = (new StyleBomTable())->whereIn('style_id', $styleIds)->orderBy('position', 'asc')->get()->toArray();
        $styleBomMap = [];
        //获取单耗
        $styleBomSizeConfigList = (new StyleBomSizeConfigTable())->whereIn('style_id', $styleIds)->get()->toArray();
        $styleBomSizeConfigMap = [];
        foreach ($styleBomSizeConfigList as $item){
            $styleBomSizeConfigMap[$item['style_id']][$item['style_bom_id']] = $item['amount'];
        }
        foreach ($styleBomList as $item){
            $attributeList = json_decode($item['materiel_attribute'], true);
            $attribute = "";
            if(!empty($attributeList)){
                foreach ($attributeList as $attr){
                    $attribute .= $attr['name'].":".$attr['value']." ";
                }
            }
            $item['materiel_attribute'] = $attribute;
            $item['amount'] = $styleBomSizeConfigMap[$item['style_id']][$item['id']] ?? 0;
            $styleBomMap[$item['style_id']][$item['is_product']][] = $item;
        }
        //获取绣花BOM
        $styleT50List = (new StyleT50Table())->whereIn('style_id', $styleIds)->orderBy('position', 'asc')->get()->toArray();
        $styleT50Map = [];
        foreach ($styleT50List as $item){
            $styleT50Map[$item['style_id']][] = $item;
        }
        //印花BOM
        $stylePrintingList = (new StylePrintingTable())->whereIn('style_id', $styleIds)->orderBy('position', 'asc')->get()->toArray();
        $stylePrintingMap = [];
        foreach ($stylePrintingList as $item){
            $attributeList = json_decode($item['materiel_attribute'], true);
            $attribute = "";
            if(!empty($attributeList)){
                foreach ($attributeList as $attr){
                    $attribute .= $attr['name'].":".$attr['value']." ";
                }
            }
            $item['materiel_attribute'] = $attribute;
            $stylePrintingMap[$item['style_id']][] = $item;
        }
        $data = [];
        foreach ($styleColourList as $item){
            //颜色相关的BOM列表
            $bomIds = $styleBomColourConfigMap[$item['style_id']][0][$item['id']] ?? [];//物料清单
            $bigBomIds = $styleBomColourConfigMap[$item['style_id']][1][$item['id']] ?? [];//大货BOM
            $bomList = [];
            $bigBomList = [];
            foreach ($styleBomMap[$item['style_id']][0] ?? [] as $bom){
                if(in_array($bom['id'], $bomIds)){
                    $bomList[] = $bom;
                }
            }
            foreach ($styleBomMap[$item['style_id']][1] ?? [] as $bom){
                if(in_array($bom['id'], $bigBomIds)){
                    $bigBomList[] = $bom;
                }
            }
            $styleObj['style'] = array_merge($styleMap[$item['style_id']], ['img' => $imageMap[$styleMap[$item['style_id']]['number']] ?? ""]);
            $styleObj['label'] = "BOM";
            $styleObj['colour'] = $item['colour'];
            $styleObj['bom'] = $bomList;//物料档案
            $styleObj['xh_bom'] = $styleT50Map[$item['style_id']] ?? [];//绣花BOM
            $styleObj['printing_bom'] = $stylePrintingMap[$item['style_id']] ?? [];//印花BOM
            $data[] = $styleObj;
            $styleObj['label'] = "大货BOM";
            $styleObj['bom'] = $bigBomList;//大货BOM
            $data[] = $styleObj;
        }
        return $data;
    }

    public function save($param)
    {
        list($form, $bomList, $itemList, $t59List, $t76List, $printingList) = [json_decode($param['form'], true), json_decode($param['bom_list'], true),
            json_decode($param['item_list'], true), json_decode($param['t59_list'], true), json_decode($param['t76_list'], true),
            json_decode($param['printing_list'], true)];
        //dd($form, $bomList, $itemList, $t59List, $t76List, $printingList);
        try{
            DB::connection("mysql_sj")->beginTransaction();
            //保存主表
            $verifyRes = $this->saveVerifyPrice($form);
            if($verifyRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $verifyRes;
            }
            //保存bom
            $verifyBomRes = $this->saveVerifyBom($bomList, $verifyRes['verify_price_id']);
            if($verifyBomRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $verifyBomRes;
            }
            //保存绣花bom
            $verifyT59Res = $this->saveVerifyT59($t59List, $verifyRes['verify_price_id']);
            if($verifyT59Res['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $verifyT59Res;
            }
            //保存印花bom
            $verifyPrintingRes = $this->saveVerifyPrinting($printingList, $verifyRes['verify_price_id']);
            if($verifyPrintingRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $verifyPrintingRes;
            }
            //保存加工项目
            $verifyItemRes = $this->saveVerifyItem($itemList, $verifyRes['verify_price_id']);
            if($verifyItemRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $verifyItemRes;
            }
            //保存其他费用
            $verifyT76Res = $this->saveVerifyT76($t76List, $verifyRes['verify_price_id']);
            if($verifyT76Res['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $verifyT76Res;
            }
            DB::connection("mysql_sj")->commit();
            return $verifyT76Res;
        }catch (\Exception $e){
            DB::connection("mysql_sj")->rollBack();
            return ['code' => -1, 'msg' => "提交失败：".$e->getMessage()];
        }
    }

    public function saveVerifyPrice($param)
    {
        $user = auth()->guard("api")->user();
        $data = [
            't73_id' => $param['t73_id'],
            'import_type' => 1,
            'import_id' => (Int)$param['import_id'],
            'import_number' => $param['import_number'],
            'style_number' => $param['style_number'],
            'style' => $param['style'],
            'colour' => $param['colour'],
            'product_category_id' => $param['product_category_id'],
            'product_category' => $param['product_category'],
            'style_detail_category_id' => $param['style_detail_category_id'],
            'style_detail_category' => $param['style_detail_category'],
            'supplier_id' => 0,
            'supplier' => '',
            'currency_id' => $param['currency_id'],
            'f8_id' => 0,
            'f8' => '',
            'f61' => (Double)$param['f61'],
            'f62' => (Double)$param['f62'],
            'f63' => (Double)$param['f63'],
            'f64' => (Double)$param['f64'],
            'f65' => (Double)$param['f65'],
            'f66' => (Double)$param['f66'],
            'f67' => (Double)$param['f67'],
            'f69' => (Double)$param['f69'],
            'f70' => (Double)$param['f70'],
            'f71' => (Double)$param['f71'],
            'f72' => (Double)$param['f72'],
            'f74' => (Double)$param['f74'],
            'f75' => (Double)$param['f75'],
            'f77' => (Double)$param['f77'],
            'f78' => (Double)$param['f78'],
            'printing_price' => (Double)$param['printing_price'],
            'comment' => $param['comment'],
            'state' => $param['state'],
            'order_date' => 0
        ];
        if($param['id'] ?? ""){
            $resp = (new VerifyPriceTable())->updateData($param['id'], $data);
            $resp['verify_price_id'] = $param['id'];
            return $resp;
        }else{
            $number5 = (new Number5Table())->first();
            $number5Data = ['head' => date('ym'), 'count' => $number5->head == date('ym') ? $number5->count + 1 : 1];
            DB::connection("mysql_sj")->table("number_5")->update($number5Data);
            $data = array_merge($data, [
                'number' => "VP".$number5Data['head'].str_pad($number5Data['count'],4,"0",STR_PAD_LEFT),
                'creator_id' => 5,//$user->id, //数加系统 用户查看权限问题，默认用户 5
                'creator' => $user->name,
                'creation_time' => strtotime(date('Y-m-d')) - 1512460800
            ]);
            $resp = (new VerifyPriceTable())->createData($data);
            $resp['verify_price_id'] = $resp['id'] ?? "";
            return $resp;
        }
    }

    public function saveVerifyBom($bomList, $verifyPriceId)
    {
        $resp = ['code' => 0];
        foreach ($bomList as $item) {
            $data = [
                'verify_price_id' => $verifyPriceId,
                'materiel_id' => $item['materiel_id'],
                'materiel' => $item['materiel'],
                'materiel_major_category' => $item['materiel_major_category'],
                'materiel_major_unit' => $item['materiel_major_unit'],
                'materiel_attribute' => $item['materiel_attribute'],
                'materiel_supply_type_id' => $item['materiel_supply_type_id'],
                'part' => $item['part'],
                'amount' => (Double)$item['amount'],
                'price' => (Double)$item['price'],
                'supplier_id' => $item['supplier_id'],
                'supplier' => $item['supplier'],
                'f56' => (Double)$item['f56'],
                'f57' => !empty($item['f57']) ? round(((Double)$item['f57'])/100, 2) : 0
            ];
            if($item['id'] ?? ""){
                $resp = (new VerifyPriceBomTable())->updateData($item['id'], $data);
            }else{
                $resp = (new VerifyPriceBomTable())->createData($data);
            }
            if($resp['code'] !== 0){
                return $resp;
            }
        }
        return $resp;
    }

    public function saveVerifyT59($t59List, $verifyPriceId)
    {
        $resp = ['code' => 0];
        foreach ($t59List as $item) {
            $data = [
                'verify_price_id' => $verifyPriceId,
                'f51' => $item['f51'],
                'part' => $item['part'],
                'f52' => (Int)$item['f52'],
                'f53' => $item['f53'],
                'f54' => (Double)$item['f54'],
                'f55' => (Double)$item['f55'],
                'f60' => !empty($item['f60']) ? round(((Double)$item['f60'])/100, 2) : 0
            ];
            if($item['id'] ?? ""){
                $resp = (new VerifyPriceT59Table())->updateData($item['id'], $data);
            }else{
                $resp = (new VerifyPriceT59Table())->createData($data);
            }
            if($resp['code'] !== 0){
                return $resp;
            }
        }
        return $resp;
    }

    public function saveVerifyPrinting($printingList, $verifyPriceId)
    {
        $resp = ['code' => 0];
        foreach ($printingList as $item) {
            $data = [
                'verify_price_id' => $verifyPriceId,
                'part' => $item['part'],
                'price' => (Double)$item['price'],
                'materiel_id' => $item['materiel_id'],
                'materiel' => $item['materiel'],
                'materiel_number' => $item['materiel_number'],
                'materiel_major_category' => $item['materiel_major_category'],
                'materiel_minor_category' => $item['materiel_minor_category'],
                'materiel_attribute' => $item['materiel_attribute'],
                'printing' => $item['printing'],
                'supplier_id' => $item['supplier_id'],
                'supplier' => $item['supplier'],
            ];
            if($item['id'] ?? ""){
                $resp = (new VerifyPricePrintingTable())->updateData($item['id'], $data);
            }else{
                $resp == (new VerifyPricePrintingTable())->createData($data);
            }
            if($resp['code'] !== 0){
                return $resp;
            }
        }
        return $resp;
    }

    public function saveVerifyItem($itemList, $verifyPriceId)
    {
        $resp = ['code' => 0];
        $ids = array_column($itemList, 'id');
        //清空删除的加工项目明细
        $delRes = (new VerifyPriceItemTable())->deleteDataWhere(['verify_price_id' => $verifyPriceId, 'id' => ['not_in' => $ids]]);
        if($delRes['code'] !== 0){
            return $delRes;
        }
        foreach ($itemList as $item){
            $data = [
                'verify_price_id' => $verifyPriceId,
                'price_type_id' => (Int)$item['price_type_id'],
                'count' => (Double)$item['count'],
                'price' => (Double)$item['price'],
                'f58' => !empty($item['f58']) ? round(((Double)$item['f58'])/100, 2) : 0
            ];
            if($item['id'] ?? ""){
                $resp = (new VerifyPriceItemTable())->updateData($item['id'], $data);
            }else{
                $resp = (new VerifyPriceItemTable())->createData($data);
            }
            if($resp['code'] !== 0){
                return $resp;
            }
        }
        return $resp;
    }

    public function saveVerifyT76($t76List, $verifyPriceId)
    {
        $resp = ['code' => 0];
        $ids = array_column($t76List, 'id');
        //清空删除的加工项目明细
        $delRes = (new VerifyPriceT76Table())->deleteDataWhere(['verify_price_id' => $verifyPriceId, 'id' => ['not_in' => $ids]]);
        if($delRes['code'] !== 0){
            return $delRes;
        }
        foreach ($t76List as $item){
            $data = [
                'verify_price_id' => $verifyPriceId,
                'price_type_id' => (Int)$item['price_type_id'],
                'count' => (Double)$item['count'],
                'price' => (Double)$item['price'],
                'f58' => !empty($item['f58']) ? round(((Double)$item['f58'])/100, 2) : 0,
                'supplier_id' => (Int)$item['supplier_id'],
                'supplier' => $item['supplier']
            ];
            if($item['id'] ?? ""){
                $resp = (new VerifyPriceT76Table())->updateData($item['id'], $data);
            }else{
                $resp = (new VerifyPriceT76Table())->createData($data);
            }
            if($resp['code'] !== 0){
                return $resp;
            }
        }
        return $resp;
    }
}
